#!/usr/bin/env python3
# encoding:utf-8
#*********************************************************************
# 本脚本适用于20.5-20.9系列的deepin操作系统配置
#*********************************************************************

import os
import sys
import time
import getpass
import subprocess
from multiprocessing import Process
import getopt

RESOURCE_DIR = os.getcwd()+"/resources"
USER = getpass.getuser()

XRANDER_CMD = "xrandr 2>/dev/null|egrep 'connected primary' 2>/dev/null|awk '{print $1}' 2>/dev/null"
SCREEN = str(subprocess.run(XRANDER_CMD,shell=True,stdout=subprocess.PIPE).stdout.strip(),'UTF-8')

XFT_DPI_CMD = "gsettings get com.deepin.xsettings xft-dpi"
DPI = str(subprocess.run(XFT_DPI_CMD,shell=True,stdout=subprocess.PIPE).stdout.strip(),'UTF-8')

SCALE_FACTOR_CMD = "gsettings get com.deepin.xsettings scale-factor"
SCALE_FACTOR = str(subprocess.run(SCALE_FACTOR_CMD,shell=True,stdout=subprocess.PIPE).stdout.strip(),'UTF-8')

XFT_DPI = "Xft/DPI %s" % DPI

EDGE_REPO = "deb [arch=amd64] https://packages.microsoft.com/repos/edge stable main"
VSCODE_REPO = "deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main"
RESIDENT_PROGRAM = "['/S@microsoft-edge','/S@deepin-terminal']"
PALLET = '{"datetime":{"Use24HourFormat":true,"pos_datetime_1":1},"grand-search":{"disabled":true,"pos_grand-search_1":1},"multitasking":{"enable":false,"pos_multitasking_1":2},"network":{"holded_network-item-key":true,"pos_network-item-key_1":1},"notifications":{"enable":false,"pos_notifications_0":3},"onboard":{"enable":false,"pos_onboard_1":2},"show-desktop":{"enable":false,"pos_show-desktop_1":2},"shutdown":{"enable":false,"pos_shutdown_1":3},"sound":{"holded_sound-item-key":true,"pos_sound-item-key_1":2},"system-monitor":{"enable":false},"trash":{"enable":false,"pos_trash_1":5},"tray":{"fashion-mode-trays-sorted":true,"fashion-tray-expanded":true,"holded_sni:Fcitx":true,"holded_sni:Nutstore":false,"holded_window:onboard":false,"pos_sni:Fcitx_1":3}}' 

unused_deepin_apps = {
    '欢迎':[True,"dde-introduction"],
    '用户反馈':[True,"deepin-feedback"],
    '社区论坛':[True,"deepin-forum"],
    '帮助手册':[True,"deepin-manual dde-manual-content"],
    '浏览器':[True,"org.deepin.browser"],
    '下载器':[True,"org.deepin.downloader"],
    '启动盘制作工具':[True,"deepin-boot-maker"],
    '磁盘管理器':[True,"deepin-diskmanager"],
    '设备管理器':[True,'deepin-devicemanager'],
    '字体管理器':[True,"deepin-font-manager"],
    '日志收集工具':[True,"deepin-log-viewer"],
    '系统监视器':[True,"deepin-system-monitor"],
    '归档管理器':[True,"deepin-compressor"],
    '文档查看器':[True,"deepin-reader"],
    '语音记事本':[True,"deepin-voice-note"],
    '打印机管理':[True,"dde-printer"],
    '画板':[True,"deepin-draw"],
    '相册':[True,"deepin-album"],
    '音乐':[True,"deepin-music"],
    '邮箱':[True,"deepin-mail"],
    '影院':[False,"deepin-movie"],
    '日历':[False,"dde-calendar"],
    '相机':[True,"deepin-camera"],
    '计算器':[True,"deepin-calculator"],
    '屏保':[True,"deepin-screensaver"],
    '壁纸':[True,"deepin-wallpapers"],
    '扫描易':[True,"simple-scan"],
    'LibreOffice办公':[True,"LibreOffice*"],
    '连连看':[True,"com.deepin.lianliankan"],
    '五子棋':[True,"com.deepin.gomoku"],
    '备份恢复':[True,"deepin-recovery-plugin deepin-ab-recovery"],
    'nano编辑':[True,"nano"],
    '快捷键预览':[False,"deepin-shortcut-viewer"],
    '全局搜索':[False,"dde-grand-search"],
    '应用商店':[False,"deepin-app-store"],
    '深度ID':[False,"deepin-deepinid-client"],
    '截图录屏':[False,"deepin-screen-recorder"],
    '看图':[False,"deepin-image-viewer"],
    '软件管理器':[False,"deepin-deb-installer"],
    '文本编辑器':[False,"deepin-editor"],
    '终端':[False,"deepin-terminal"],
    '深度之家':[True,"deepin-home"],
}

unused_deepin_themes = {
    'Papirus主题':[True,"/usr/share/icons/Papirus"],
    'Vintage主题':[True,"/usr/share/icons/Vintage"],
    'Adwaita主题':[True,"/usr/share/icons/Adwaita"],
    'bloom-dark主题':[True,"/usr/share/icons/bloom-dark"],
    'bloom-classic主题':[True,"/usr/share/icons/bloom-classic*"],
    'ubuntu-mono主题':[True,"/usr/share/icons/ubuntu-mono*"],
    'gnome主题':[True,"/usr/share/icons/gnome"],
    'deepin主题':[True,"/usr/share/icons/deepin"],
}

#常用软件和环境部署
common_apps = {
    'Fcitx5':{
        'descriptioin':"安装和配置fcitx5",
        'execute':True,
        'steps':[
            #卸载fcitx,安装fcitx5
            "sudo apt -y purge fcitx* >/dev/null 2>&1","sudo apt -y autoremove >/dev/null 2>&1",
            "sudo apt -y install fcitx5 fcitx5-chinese-addons >/dev/null 2>&1",
            #配置主题
            "sudo cp -r %s/fcitx5/theme/* /usr/share/fcitx5/themes/" % RESOURCE_DIR,
            "sudo cp /usr/share/fcitx5/themes/meterial/theme-blue.conf /usr/share/fcitx5/themes/meterial/theme.conf",
            #配置符号
            "sudo cp -r %s/fcitx5/misc/punc.mb.zh_CN /usr/share/fcitx5/punctuation/" % RESOURCE_DIR,
            #添加词库
            "mkdir -p /home/%s/.local/share/fcitx5/pinyin/dictionaries/" % USER,
            "cp -r %s/fcitx5/dictionaries/* /home/%s/.local/share/fcitx5/pinyin/dictionaries/" % (RESOURCE_DIR,USER),
            #启动器图标隐藏
            "sudo sh -c 'echo NoDisplay=true >> /usr/share/applications/kbd-layout-viewer5.desktop'",
            "sudo sh -c 'echo NoDisplay=true >> /usr/share/applications/org.fcitx.Fcitx5.desktop'",
            #载入个性化配置
            "rm -rf /home/%s/.config/fcitx5/*" % USER,
            "mkdir -p /home/%s/.config/fcitx5" % USER,
            "cp -r %s/fcitx5/config/* /home/%s/.config/fcitx5" % (RESOURCE_DIR,USER),
            #修复任务栏启动配置界面样式问题,配置/etc/environment文件
            "sudo cp -r %s/fcitx5/environment /etc/environment" % RESOURCE_DIR,
            #修复20.9无法打开配置文件的问题
            "sudo ln -fs /usr/bin/fcitx5-config-qt /usr/bin/fcitx5-configtool",
        ],
    },
    '增加better-dde源,更新fcitx5':{
        'descriptioin': "增加better-dde源,更新fcitx5",
        'execute':False,
        'steps': [
            'wget -q -O - "http://120.132.17.134:3000/better-dde/ppa/raw/branch/master/better-dde.gpg" | gpg --dearmor | sudo tee /etc/apt/trusted.gpg.d/better-dde-keyring.gpg',
            "sudo cp %s/fcitx5/better-dde.list /etc/apt/sources.list.d/" % RESOURCE_DIR,
            "sudo apt update >/dev/null 2>&1",
            "sudo apt install --only-upgrade fcitx5* >/dev/null 2>&1",
            "sudo rm -rf /etc/apt/sources.list.d/better-dde.list",
        ],  
    }, 
    '修复缺失图标':{
        'descriptioin':"修复因删除主题缺失的图标",
        'execute':True,
        'steps':[
            "sudo cp %s/fcitx5/icon/english.svg /usr/share/icons/bloom/status/48/input-keyboard-symbolic.svg" % RESOURCE_DIR,
            "sudo cp %s/fcitx5/icon/input-keyboard-symbolic.svg /usr/share/icons/bloom/status/48/input-keyboard.svg" % RESOURCE_DIR,
            "sudo cp %s/fcitx5/icon/chinese.svg /usr/share/icons/bloom/status/48/fcitx-pinyin.svg" % RESOURCE_DIR,
        ],
    },
    '微信':{
        'descriptioin':"安装微信",
        'execute':True,
        'steps':["sudo apt install -y com.qq.weixin.deepin >/dev/null 2>&1"],
    },
    'WPS办公':{
        'descriptioin':"安装wps办公",
        'execute':True,
        'steps':[
            "sudo apt install -y cn.wps.wps-office >/dev/null 2>&1",
            "rm -rf /home/%s/Desktop/wps-office-*.desktop" % USER,
            "rm -rf /home/%s/.Templates/*" % USER,
        ],
    },
    '网易云音乐':{
        'descriptioin':"安装网易云音乐",
        'execute':False,
        'steps':[
            "sudo apt install -y com.163.music >/dev/null 2>&1",
            "sudo sed -i 's/Exec=/Exec= env QT_SCALE_FACTOR=%s '/g /opt/apps/com.163.music/entries/applications/com.163.music.desktop"  % SCALE_FACTOR,
        ],
    },
    'Edge浏览器':{
        'descriptioin':"安装edge浏览器",
        'execute':True,
        'steps':[
            "wget -q -O - https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add - >/dev/null 2>&1",
            "sudo sh -c 'echo %s > /etc/apt/sources.list.d/microsoft-edge.list'" % EDGE_REPO,
            "sudo apt -y update",
            "sudo apt -y install microsoft-edge-stable >/dev/null 2>&1",
        ],
    },
    'vscode编辑器':{
        'descriptioin':"安装vscode编辑器",
        'execute':False,
        'steps':[
            "sudo sh -c 'echo %s >/etc/apt/sources.list.d/vscode.list'" % VSCODE_REPO,
            "sudo apt -y update",
            "sudo apt -y install code",
        ],
    },
    'typora':{
        'descriptioin':"安装typora编辑器",
        'execute':True,
        'steps':[
            "sudo apt install -y io.typora",
            "sudo sed -i 's/Icon=typora/Icon=io.typora.png/g' /opt/apps/io.typora/entries/applications/io.typora.desktop",
        ],
    },
    '为知笔记':{
        'descriptioin':"安装为知笔记",
        'execute':False,
        'steps':[
            "wget https://url.wiz.cn/u/linux_new -O WizNote.AppImage >/dev/null 2>&1",
            "sudo mkdir -p /opt/apps/cn.wiz",
            "sudo cp WizNote.AppImage /opt/apps/cn.wiz/wiznote.AppImage",
            "cp %s/wiznote/wiznote.png /home/%s/.icons/" % (RESOURCE_DIR,USER),
            "sudo cp %s/wiznote/wiznote.desktop /usr/share/applications/" % RESOURCE_DIR,
            "sudo chmod +x /opt/apps/cn.wiz/wiznote.AppImage",
            "rm -rf WizNote.AppImage",
        ],
    },
    '坚果云':{
        'descriptioin':"安装坚果云",
        'execute':False, 
        'steps':[
            "sudo apt install -y com.nutstore.deepin",
        ],
    },
    '百度网盘':{
        'descriptioin':"安装百度网盘",
        'execute':False,
        'steps':[
            "sudo apt -y install com.baidu.baidunetdisk",
            "sudo rm -rf /usr/share/dde-file-manager/extensions/appEntry/com.baidu.baidunetdiskv_uos.desktop",
        ],
    },
    'kvm虚拟化':{
        'descriptioin':"安装kvm虚拟化环境",
        'execute':False,
        'steps':["sudo apt -y install qemu-system-x86 virt-manager"],
    },
    'dokcer容器':{
        'descriptioin':"安装docker容器环境",
        'execute':False,
        'steps':["sudo apt -y install docker-ce"],
    },
    'nodejs':{
        'descriptioin':"安装nodejs环境",
        'execute':False,
        'steps':["sudo apt install nodejs npm"],
    },
    'python3':{
        'descriptioin':"安装python3环境",
        'execute':True,
        'steps':["sudo apt -y install python3-pip python3-requests"],
    },
}

#个性化配置
personalization = {
    '字体安装':{
        'descriptioin':"安装微软雅黑和Consolas字体",
        'execute':True,
        'steps':[
            "mkdir -p /home/%s/.local/share/fonts" % USER,
            "cp -r %s/fonts/* /home/%s/.local/share/fonts/" % (RESOURCE_DIR,USER),
            "sudo cp -r %s/fonts/* /usr/share/fonts/" % RESOURCE_DIR,
        ],
    },
    '壁纸设置':{
        'descriptioin':"桌面壁纸设置",
        'execute':True,
        'steps':[
            "busctl --user call \
            com.deepin.daemon.Appearance /com/deepin/daemon/Appearance com.deepin.daemon.Appearance \
            SetMonitorBackground ss '%s' '%s/pictures/desktop.jpg'" % (SCREEN,RESOURCE_DIR),
        ],
    },
    '背景图片':{
        'descriptioin':"背景图片设置",
        'execute':True,
        'steps':[
            "sudo cp %s/pictures/background.jpg /usr/share/backgrounds/default_background.jpg" % RESOURCE_DIR,
            "for img in $(ls /var/cache/deepin/dde-daemon/image-effect/pixmix/);\
            do sudo cp %s/pictures/background.jpg /var/cache/deepin/dde-daemon/image-effect/pixmix/${img};\
            sudo chmod 600 /var/cache/deepin/dde-daemon/image-effect/pixmix/${img};done" % RESOURCE_DIR,
            "sudo chmod 400 /var/cache/deepin/dde-daemon/image-effect/pixmix",
        ],
    },
    '图像设置':{
        'descriptioin':"用户图像设置",
        'execute':True,
        'steps':[
            "sudo rm -rf /var/lib/AccountsService/icons/*.png",
            "sudo rm -rf /var/lib/AccountsService/icons/bigger/*.png",
            "busctl --system \
            call com.deepin.daemon.Accounts /com/deepin/daemon/Accounts/User1000 com.deepin.daemon.Accounts.User \
            SetIconFile s '%s/pictures/account.jpg'" % RESOURCE_DIR,
        ],
    },
    '启动器图标':{
        'descriptioin':"启动器图标设置",
        'execute':True,
        'steps':[
            "for size in 16 24 32 48 64 96 128 256 512; \
            do sudo cp %s/pictures/deepin-launcher.svg /usr/share/icons/bloom/places/${size}/deepin-launcher.svg;\
            done" % RESOURCE_DIR,
        ],
    },
    'sudo免密':{
        'descriptioin':"设置sudo免密",
        'execute':True,
        'steps':[
            "sudo sed -i 's/\%sudo\tALL=(ALL:ALL) ALL/\%sudo\tALL=(ALL:ALL) NOPASSWD:ALL/g' /etc/sudoers",
            "sudo usermod -a -G sudo %s" % USER,
        ],
    },
    '控制中心字体':{
        'descriptioin':"设置字体",
        'execute':True,
        'steps':["gsettings set com.deepin.dde.appearance font-standard 'Microsoft YaHei UI'"],
    },
    '控制中心电源':{
        'descriptioin':"设置电源策略",
        'execute':True,
        'steps':[
            "gsettings set com.deepin.dde.power battery-lid-closed-action 'turnOffScreen'",
            "gsettings set com.deepin.dde.power battery-lock-delay 0",
            "gsettings set com.deepin.dde.power battery-screen-black-delay 0",
            "gsettings set com.deepin.dde.power battery-sleep-delay 0",
            "gsettings set com.deepin.dde.power line-power-lid-closed-action 'turnOffScreen'",
            "gsettings set com.deepin.dde.power line-power-lock-delay 0",
            "gsettings set com.deepin.dde.power line-power-screen-black-delay 0",
            "gsettings set com.deepin.dde.power line-power-sleep-delay 0",
        ],
    },
    '控制中心圆角':{
        'descriptioin':"设置圆角级别",
        'execute':True,
        'steps':["gsettings set com.deepin.xsettings dtk-window-radius 8",],
    },
    '控制中心快捷键':{
        'descriptioin':"设置全局快捷键",
        'execute':True,
        'steps':[
            #终端快捷键
            'busctl --user call \
            com.deepin.daemon.Keybinding /com/deepin/daemon/Keybinding com.deepin.daemon.Keybinding \
            DeleteShortcutKeystroke sis "switch-to-workspace-2" 3 "<Super>2"',
            'busctl --user call \
            com.deepin.daemon.Keybinding /com/deepin/daemon/Keybinding com.deepin.daemon.Keybinding \
            ModifiedAccel sisb "terminal" 0 "<Super>2" true',
            'gsettings set com.deepin.dde.keybinding.system terminal "[\'<Super>2\']"',
            #edge快捷键
            'busctl --user call \
            com.deepin.daemon.Keybinding /com/deepin/daemon/Keybinding com.deepin.daemon.Keybinding \
            DeleteShortcutKeystroke sis "switch-to-workspace-1" 3 "<Super>1" ',
            'busctl --user call \
            com.deepin.daemon.Keybinding /com/deepin/daemon/Keybinding com.deepin.daemon.Keybinding \
            AddCustomShortcut sss "edge" "/opt/microsoft/msedge/msedge" "<Super>1"',
            #微信快捷键
            #'busctl --user call \
            #com.deepin.daemon.Keybinding /com/deepin/daemon/Keybinding com.deepin.daemon.Keybinding \
            #AddCustomShortcut sss "wechat" "/opt/deepinwine/tools/sendkeys.sh w WeChat" "<Alt>W"',
        ],
    },
    '终端':{
        'descriptioin':"替换终端为自编译终端",
        'execute':True,
        'steps':[
            "sudo cp %s/deepin-terminal/deepin-terminal /usr/bin/deepin-terminal.%s" % (RESOURCE_DIR,USER),
            "sudo cp %s/deepin-terminal/deepin-terminal_zh_CN.qm /usr/share/deepin-terminal/translations/deepin-terminal_zh_CN.qm" % RESOURCE_DIR,
            "sudo ln -fs /usr/bin/deepin-terminal.%s /usr/bin/deepin-terminal" % USER,
            "sudo cp %s/deepin-terminal/*.colorscheme /usr/share/terminalwidget5/color-schemes/" % RESOURCE_DIR,
            "sudo cp %s/deepin-terminal/lscolor-256color /etc/" % RESOURCE_DIR,
            "sudo cp %s/deepin-terminal/libterminalwidget5.so.0.14.1 /lib/x86_64-linux-gnu/libterminalwidget5.so.0.14.1.%s" % (RESOURCE_DIR,USER),
            "sudo ln -fs /lib/x86_64-linux-gnu/libterminalwidget5.so.0.14.1.%s /lib/x86_64-linux-gnu/libterminalwidget5.so.0.14.1" % USER,
            "cp %s/deepin-terminal/config.conf /home/%s/.config/deepin/deepin-terminal/" % (RESOURCE_DIR,USER),
            "sudo chmod +x /usr/bin/deepin-terminal.%s" % USER,
        ],
    },
    '任务栏模式':{
        'descriptioin':"设置任务栏高效模式",
        'execute':True,
        'steps':[
            "gsettings set com.deepin.dde.dock display-mode 'efficient'",
        ],
    },
    '任务栏驻留':{
        'descriptioin':"设置任务栏驻留",
        'execute':True,
        'steps':[
            'gsettings set com.deepin.dde.dock docked-apps "%s"' % RESIDENT_PROGRAM,
        ],
    },
    '任务栏托盘':{
        'descriptioin':"取消托盘隐藏",
        'execute':True,
        'steps':[
            "gsettings set com.deepin.dde.dock plugin-settings %s" % PALLET,
            "busctl --user call \
            com.deepin.dde.daemon.Dock /com/deepin/dde/daemon/Dock com.deepin.dde.daemon.Dock \
            SetPluginSettings s '%s'" % PALLET,
        ],
    },
    '任务栏取消键盘布局图标':{
        'descriptioin':"取消任务栏键盘布局图标",
        'execute':True,
        'steps':[
            "gsettings set com.deepin.dde.dock.module.keyboard enable false",
        ],
    },
    '任务栏插件':{
        'descriptioin':"取消任务栏插件",
        'execute':True,
        'steps':[
            "for i in '回收站' '系统监视器' '电源' '显示桌面' '屏幕键盘' '通知中心' '多任务视图' '全局搜索' '截图录屏'; \
            do busctl --user call com.deepin.dde.Dock /com/deepin/dde/Dock com.deepin.dde.Dock setPluginVisible sb ${i} false; \
			done"
        ],
    },
    '任务栏时间':{
        'descriptioin':"调整任务栏时间格式",
        'execute':True,
        'steps':[
            "gsettings set com.deepin.dde.datetime short-date-format 3",
        ],
    },
    'vimrc':{
        'descriptioin':"配置vimrc",
        'execute':True,
        'steps':[
            "cp %s/vim/vimrc /home/%s/.vimrc" % (RESOURCE_DIR,USER),
            "sudo cp %s/vim/vimrc /root/.vimrc" % (RESOURCE_DIR),
        ],
    },
    'bashrc':{
        'descriptioin':"配置bashrc",
        'execute':True,
        'steps':[
            "cp %s/bash/bashrc /home/%s/.bashrc" % (RESOURCE_DIR,USER),
        ],
    },
    '锁屏界面':{
        'descriptioin':"配置锁屏界面字体",
        'execute':True,
        'steps':[
            "sudo cp %s/xsettings/xsettingsd.conf /etc/lightdm/deepin/xsettingsd.conf" % RESOURCE_DIR,
            "sudo sh -c 'echo %s >> /etc/lightdm/deepin/xsettingsd.conf'" % XFT_DPI,
        ],
    },
    '引导界面':{
        'descriptioin':"配置系统引导界面",
        'execute':True,
        'steps':[
            "sudo sed -i 's/GRUB_TIMEOUT=1/GRUB_TIMEOUT=0/g' /etc/default/grub",
            "sudo sed -i '/GRUB_BACKGROUND/d' /etc/default/grub",
            "sudo sed -i '/GRUB_THEME/d' /etc/default/grub",
            "sudo update-grub >/dev/null 2>&1",
        ],
    },
    '创建右键新建文档模板':{
        'descriptioin':"右键新建文档模板",
        'execute':True,
        'steps':[
            "sudo mkdir -p /usr/share/templates/source",
            "sudo cp %s/right_click/templates/*.desktop /usr/share/templates/" % RESOURCE_DIR,
            "sudo cp %s/right_click/templates/source/* /usr/share/templates/source/" % RESOURCE_DIR,
        ],
    },
    '右键发送到':{
        'descriptioin':"添加右键发送到",
        'execute':True,
        'steps':[
            "mkdir -p /home/%s/.%s/deepin-send-to/" % (USER,USER),
            "cp -r %s/right_click/deepin-send-to/cnblogs.com /home/%s/.%s/deepin-send-to/" % (RESOURCE_DIR,USER,USER),
            "cp -r %s/right_click/deepin-send-to/wiz.cn /home/%s/.%s/deepin-send-to/" % (RESOURCE_DIR,USER,USER),
            "sudo cp %s/right_click/deepin-send-to/deepin-send-to.desktop /usr/share/deepin/dde-file-manager/oem-menuextensions/" % RESOURCE_DIR,
            "cp -r %s/pictures/cnblogs.png /home/%s/.icons/" % (RESOURCE_DIR,USER),
            "cp -r %s/pictures/yuque.png /home/%s/.icons/" % (RESOURCE_DIR,USER),
            "cp -r %s/wiznote/wiznote.png /home/%s/.icons/" % (RESOURCE_DIR,USER),
        ],
    },
    '创建ctrl+d删除文件快捷键':{
        'descriptioin':"使用xdotools创建ctrl+d删除文件的快捷键",
        'execute':True,
        'steps':[
            "mkdir -p /home/%s/.%s/deepin/" % (USER,USER),
            "cp -r %s/scripts/ctrld.sh /home/%s/.%s/deepin/" % (RESOURCE_DIR,USER,USER),
            'busctl --user call \
			com.deepin.daemon.Keybinding /com/deepin/daemon/Keybinding com.deepin.daemon.Keybinding \
			AddCustomShortcut sss "ctrl+d" "/bin/bash /home/%s/.%s/deepin/ctrld.sh" "<Control>D"' % (USER,USER),
        ],
    },
}

###

def execute(Dict,info="",cmd=""):
    rtn = {}
    for k,v in Dict.items():
        rtn.update({'%s' % k:{'descriptioin':"%s%s" % (info,k),'execute':v[0],'steps':["%s %s >/dev/null 2>&1" % (cmd,v[1])]}})
    return rtn

def create_apt_purge_deepin_apps_dict(appDict):
    """
    卸载不需要的软件
    """
    return execute(Dict=appDict,info="卸载",cmd="sudo apt purge -y")

def create_unused_deepin_theme(themeDict):
    """
    删除不需要的主题
    """
    return execute(Dict=themeDict,info="删除",cmd="sudo rm -rf ")

def create_install_app_from_store(appDict):
    """
    从商店安装应用
    """
    return execute(Dict=appDict,info="安装",cmd="sudo apt -y install")

def process_bar(bar):
    print("%s" % bar,end="")

def execute_modify(obj_dict,answer=False):
    """
    交互/非交互
    """
    descriptioin = obj_dict.get('descriptioin')
    execute = obj_dict.get('execute')
    steps = obj_dict.get('steps')

    #False的内容直接跳过
    if execute is False:
        return

    #打印分隔符
    #print("|--->")
    for i in range(81):
        print("*",end="")
    print("")

    #获取交互
    if answer:
        auto = "y"
    else:
        auto = input("是否执行:%s(y/n)?" % descriptioin)
    if auto == "y" or auto == "":
        print("开始执行:%s" % descriptioin)
        step_rtn = True
        for step in steps:
            print("执行操作:%s" % " ".join(step.split()))
            print("执行进度:",end="")
            p = subprocess.Popen(step,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
            #p = subprocess.Popen(step,shell=True)
            while None == p.poll():
                show_process_bar = Process(target=process_bar,args=("#",))
                show_process_bar.start()
                show_process_bar.join()
                time.sleep(1)
            if p.returncode == 0:
                step_rtn = step_rtn and True
                print(" [成功].")
            else:
                step_rtn = step_rtn and False
                print(" [失败]!")

        if step_rtn:
            print("执行结果:%s [成功]." % descriptioin)
            return True
        else:
            print("执行结果:%s [失败]!" % descriptioin)
            return False
    else:
        print("不执行:%s" % descriptioin)

def system_slimming(answer=False):
    #原创应用卸载
    for v in create_apt_purge_deepin_apps_dict(unused_deepin_apps).values():
        execute_modify(v,answer)
    #主题删除
    for v in create_unused_deepin_theme(unused_deepin_themes).values():
        execute_modify(v,answer=True)
    #修复缺失的图标
    for k,v in common_apps.items():
        if k == "修复缺失图标":
            execute_modify(v,answer)


def my_common_app(answer=False):
    #常用软件安装
    for v in common_apps.values():
        execute_modify(v,answer)

def my_personalization(answer=False):
    #个性化设置
    for v in personalization.values():
        execute_modify(v,answer)

def script_info():
    print("python3 %s:[-s|-c|-p|-a] [-y]" % sys.argv[0])
    print("-a:全部执行;\n-s:系统瘦身;\n-c:常用软件安装;\n-p:个性化配置;\n-y:无交互执行")

if __name__ == "__main__":
    if len(sys.argv) == 1:
        script_info()
        sys.exit(0)
    try:
        a = input("是否已经调整脚本，配置True或者False(y/n)?")
        if a != 'y':
            sys.exit(0)
        subprocess.run("sudo apt",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
        print("\n")
        opts,args = getopt.getopt(sys.argv[1:],"scpay")
        try:
            for o,a in opts:
                if o == "-y":
                    answer = True
                else:
                    answer = False
            for o,a in opts:
                if o == "-a":
                    system_slimming(answer)
                    my_common_app(answer)
                    my_personalization(answer)
                    sys.exit(0)
                elif o == "-s":
                    system_slimming(answer)
                elif o == "-c":
                    my_common_app(answer)
                elif o == "-p":
                    my_personalization(answer)
            #subprocess.run("sudo reboot",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
        except KeyboardInterrupt:
            print("\n手动终止,退出")
    except getopt.GetoptError:
        script_info()
